package com.hns.can.service.web;

import java.io.File;
import java.io.Writer;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hns.can.base.entity.SysUserEntity;
import com.hns.can.common.entity.BaseEntity;
import com.hns.can.common.service.CommonInitParamService;
import com.hns.can.common.vo.CommonParamsVo;
import com.hns.can.common.web.BaseController;
import com.hns.can.master.entity.BaseLineInfoEntity;
import com.hns.can.service.entity.BaseDriverExamInfoEntity;
import com.hns.can.service.entity.BaseDriverExamUploadErrEntity;
import com.hns.can.service.enumrate.ParseDrvExamExcel;
import com.hns.can.service.enumrate.ParseZhenBaoDrvAttExecl;
import com.hns.can.service.processor.UptEnerConsProcessor;
import com.hns.can.service.service.BaseDriverExamInfoService;
import com.hns.can.service.service.CheckDrvExamFilter;

import com.hns.tool.export.ExportUtil;
import com.hns.tool.export.excel.excelNoTemplate.ExportExcelNoTempEntity;
import com.hns.tool.export.excel.excelTemplate.ExcelTemplate;
import com.hns.tool.export.pdf.ExportPdfEntity;
import com.hns.tool.pub.DateTool;
import com.hns.tool.pub.FileUploadUtil;
import com.hns.tool.pub.SearchConditionVo;
import com.hns.tool.pub.UtilString;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.hns.can.common.domain.GridPage;
import com.hns.frame.enumrate.MsgType;
import com.hns.frame.exception.BusinessException;
import com.hns.frame.mybatis.Pagination;
import com.hns.frame.util.ResponseUtil;
import com.hns.tool.pub.PubUtil;

/**
 * @版权：HNS 版权所有 (c) 2013
 * @author:JeffXu
 * @version Revision 1.0.0
 * @email:835264047@qq.com
 * @see:
 * @创建日期：2014-8-6
 * @功能说明：驾驶员考勤控制类
 * @begin
 * @修改记录:
 * @修改后版本          修改人      	修改内容
 * @2014-8-6  	         JeffXu        	创建
 * @end
 */
@Controller
@RequestMapping("/baseDriverExamInfo")
public class BaseDriverExamInfoController extends BaseController {
	
	@Autowired
    private BaseDriverExamInfoService baseDriverExamInfoService;
	@Autowired
	private CheckDrvExamFilter checkDrvExamFilter;
	@Autowired
    private TaskExecutor taskExecutor;
	@Autowired
    private CommonInitParamService commonInitParamService;

	
	
    /**
     * 导出文件表头
     */
    private final String[] tableHeaderNames={"运营线路", "驾驶员", "考勤卡号","车牌号","车辆编号","签到时间","签退时间","工作时长"};
    /**
     * 导出文件字段名
     */
    private final String[] tableHeaderFields={"lineName","drvName","timecardCardno","carName","carInCd","signInTime","signOutTime","workDura"};


    /**
     * @param conditionVo
     * @throws Exception
     * @author:JeffXu
     * @email:835264047@qq.com
     * @创建日期:2014-8-6
     * @功能说明：根据驾驶员ids获取驾驶员考勤列表
     */
    @RequestMapping("/searchDriverExamInfoPage")
    @ResponseBody
    public Object searchDriverExamInfoPage(CommonParamsVo commonParamsVo) throws Exception {
    	//替换参数
    	SysUserEntity user = this.getCurrentUser().getUser();
    	List<String> tabList = null ;
    	commonInitParamService.initParams(commonParamsVo, user, tabList);
        Pagination page = baseDriverExamInfoService.searchDriverExamInfoPage(commonParamsVo);
        GridPage grid = new GridPage(page);
        return this.getReturnResult(grid);
    }
    
    /**
     * @param conditionVo
     * @param response
     * @throws Exception
     * @author:JeffXu
     * @email:835264047@qq.com
     * @创建日期:2014-8-6
     * @功能说明：导出excel文件
     */
    @RequestMapping("/exportBaseDriverExam2Excel")
    public void exportBaseDriverExam2Excel(CommonParamsVo commonParamsVo,
                HttpServletResponse response) throws Exception {
        if(PubUtil.isEmpty(commonParamsVo.getOrgIds()))
            throw new BusinessException(MsgType.WARN.getFlag(), "请至少选择一个驾驶员!");
        List<BaseDriverExamInfoEntity> list = baseDriverExamInfoService.getBaseDriverExamInfoList(commonParamsVo);
        if(PubUtil.isEmpty(list))
            throw new BusinessException(MsgType.WARN.getFlag(), "没有数据导出！");
        ExportExcelNoTempEntity exportEntity = new ExportExcelNoTempEntity(
        		Arrays.asList(tableHeaderNames), Arrays.asList(tableHeaderFields), list, URLEncoder.encode("驾驶员考勤", "UTF-8")+DateTool.getCurrentSysDate("yyyyMMddHHmmss"));
            ExportUtil.generatorExcelNoTemplate(exportEntity, response);
    }
    
    /**
     * @param conditionVo
     * @param response
     * @throws Exception
     * @author:JeffXu
     * @email:835264047@qq.com
     * @创建日期:2014-8-6
     * @功能说明：导出pdf文件
     */
    @RequestMapping("/exportBaseDriverExam2Pdf")
    public void exportBaseDriverExam2Pdf(CommonParamsVo commonParamsVo,
                HttpServletResponse response) throws Exception {
        if(PubUtil.isEmpty(commonParamsVo.getOrgIds()))
            throw new BusinessException(MsgType.WARN.getFlag(), "请至少选择一个驾驶员!");
        List<BaseDriverExamInfoEntity> list = baseDriverExamInfoService.getBaseDriverExamInfoList(commonParamsVo);
        if(PubUtil.isEmpty(list))
            throw new BusinessException(MsgType.WARN.getFlag(), "没有数据导出！");
        ExportPdfEntity pdfEntity = new ExportPdfEntity(
        		Arrays.asList(tableHeaderNames), Arrays.asList(tableHeaderFields), list, URLEncoder.encode("驾驶员考勤", "UTF-8")+DateTool.getCurrentSysDate("yyyyMMddHHmmss"));
            ExportUtil.generatorPDF(pdfEntity, response);
    }
    
    /**
     * @param attendId
     * @param request
     * @param response
     * @throws Exception
     * @author:JeffXu
     * @email:835264047@qq.com
     * @创建日期:2014-7-2
     * @功能说明：删除驾驶员考勤记录
     */
    @RequestMapping("/delDriverExamInfo")
    @ResponseBody
    public Object delDriverExamInfo(@RequestParam("attendId") String attendId,
                HttpServletRequest request, HttpServletResponse response) throws Exception {
        baseDriverExamInfoService.delDriverExamInfo(attendId);
        return this.getReturnMsg("删除成功");
    }
    
    /**
     * @param attendIds
     * @param request
     * @param response
     * @throws Exception
     * @author:JeffXu
     * @email:835264047@qq.com
     * @创建日期:2014-10-16
     * @功能说明：批量删除驾驶员考勤记录
     */
    @RequestMapping("/delDriverExamInfoByAttendIds")
    @ResponseBody
    public Object delDriverExamInfo(@RequestParam("attendIds") List<String> attendIds,
                HttpServletRequest request, HttpServletResponse response) throws Exception {
        baseDriverExamInfoService.delDriverExamInfoByAttendIds(attendIds);
        return this.getReturnMsg("删除成功");
    }
    
    /**
     * @param lineId
     * @param request
     * @param response
     * @throws Exception
     * @author:JeffXu
     * @email:835264047@qq.com
     * @创建日期:2014-7-3
     * @功能说明：通过线路id获得线路信息
     */
    @RequestMapping("/getLineInfoByLineId")
    @ResponseBody
    public Object getLineInfoByLineId(@RequestParam("lineId") String lineId,
                HttpServletRequest request, HttpServletResponse response) throws Exception {
        BaseLineInfoEntity entity = baseDriverExamInfoService.getLineInfoByLineId(lineId);
        return this.getReturnResult(entity);
    }
    
    /**
     * @param lineId
     * @param carIds
     * @param drvIds
     * @param signInTimes
     * @param signOutTimes
     * @throws Exception
     * @author:JeffXu
     * @email:835264047@qq.com
     * @创建日期:2014-7-4
     * @功能说明：批量新增驾驶员考勤信息
     */
    @RequestMapping("/addDrvExam")
    @ResponseBody
    public Object addDrvExam(
        @RequestParam("lineId") String lineId, 
        @RequestParam("carIds") String[] carIds, 
        @RequestParam("drvIds") String[] drvIds, 
        @RequestParam("signInTimes") String[] signInTimes, 
        @RequestParam("signOutTimes") String[] signOutTimes) throws Exception {
        baseDriverExamInfoService.addDrvExam(lineId, carIds, drvIds, signInTimes, signOutTimes);
        return this.getReturnResult("新增成功");
    }
    
    /**
     * @param uptAttendId
     * @param uptSignInTime
     * @param uptSignOutTime
     * @param request
     * @param response
     * @throws Exception
     * @author:JeffXu
     * @email:835264047@qq.com
     * @创建日期:2014-7-4
     * @功能说明：修改驾驶员考勤信息
     */
    @RequestMapping("/uptDrvExam")
    @ResponseBody
    public Object uptDrvExam(
        @RequestParam("uptAttendId") String uptAttendId, 
        @RequestParam("uptSignInTime") String uptSignInTime, 
        @RequestParam("uptSignOutTime") String uptSignOutTime, 
                HttpServletRequest request, HttpServletResponse response) throws Exception {
        baseDriverExamInfoService.uptDrvExam(request, uptAttendId, uptSignInTime, uptSignOutTime);
        return this.getReturnResult("修改成功");
    }
    
    /**
     * @param drvExamFile
     * @param request
     * @param response
     * @throws Exception
     * @author:JeffXu
     * @email:835264047@qq.com
     * @创建日期:2014-8-18
     * @功能说明：导入文件，点击上传
     */
    @RequestMapping("/uploadDrvExamFile")
    @ResponseBody
    public Object uploadDrvExamFile(
//        @RequestParam(value = "corpId", required = false) String corpId,
        @RequestParam(value = "drvExamFile", required = false) MultipartFile drvExamFile,
                HttpServletRequest request, HttpServletResponse response,String corpId) throws Exception {
        /*// 将excel文件存盘
        response.setCharacterEncoding(encode);
        response.setContentType("text/html; charset=" + encode);
        Writer writer = null;
        try {
            writer = response.getWriter();
            writer.write("{\"code\":" + state.getCode() +",\"message\":\"" + state.getMessage()+ "\"}");
            writer.flush();
            writer.close();
        } catch(Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            IOUtils.closeQuietly(writer);
        }*/
       SysUserEntity user = this.getCurrentUser().getUser();
        String oldFileName = drvExamFile.getOriginalFilename();
        String newFileName = UtilString.getUUID() + oldFileName.substring(oldFileName.lastIndexOf("."));
        String targetPath = FileUploadUtil.getWebRoot(request) + "/template/temp/";
        FileUploadUtil.uploadFile(drvExamFile.getInputStream(), newFileName, targetPath);
        // 解析excel文件得到list对象
        String fileName = targetPath + newFileName; // 完整路径
        File file = new File(fileName);
        boolean hasAbnormalData = false;
        int count = 0;
        if("8650bf67257a49fc9bdcebec6555ac44".equals(corpId)){
        	List<BaseDriverExamInfoEntity> list = ParseZhenBaoDrvAttExecl.parseZhenBaoExcelToList(file);
        	count = baseDriverExamInfoService.saveToDB(list,corpId,user);
        }else{
        	List<BaseDriverExamUploadErrEntity> list = ParseDrvExamExcel.parseExcelToList(file);
            // 校验导入的数据
            hasAbnormalData = checkDrvExamFilter.doCheck(corpId, list);
            // 存入对应的库表
            baseDriverExamInfoService.saveToDB(corpId, list);
            
//            if(PubUtil.isNotEmpty(conditionVo)){
//                UptEnerConsProcessor processor = new UptEnerConsProcessor(taskExecutor, baseDriverExamInfoService, conditionVo);
//                processor.process();// 对应更新能耗表信息
//            }
        }
//        // 删除临时文件
//        FileUploadUtil.delFile(fileName);
        String msg = "文件数据已全部导入！";
        if(hasAbnormalData){
            msg = "文件数据部分导入，请在'错误信息查看'中进行编辑，重新导入。";
        }
        if(count>1){
        	msg = "文件数据已全部导入,共"+count+"行！";
        }
        return this.getReturnMsg(msg);
    }
    
    /**
     * @param uptErrorIds
     * @param uptOprtLines
     * @param uptLicPltNos
     * @param uptDrvNames
     * @param uptTimecardCardnos
     * @param uptSignInTimes
     * @param uptSignOutTimes
     * @throws Exception
     * @author:JeffXu
     * @email:835264047@qq.com
     * @创建日期:2015-1-19
     * @功能说明：重新导入修改后的考勤信息
     */
    @RequestMapping("/reuploadDriverExam")
    @ResponseBody
    public Object reuploadDriverExam(
//        @RequestParam(value = "corpId", required = true) String corpId,
        @RequestParam("uptErrorIds") String[] uptErrorIds, 
        @RequestParam("uptOprtLines") String[] uptOprtLines, 
        @RequestParam("uptLicPltNos") String[] uptLicPltNos, 
        @RequestParam("uptDrvNames") String[] uptDrvNames, 
        @RequestParam("uptTimecardCardnos") String[] uptTimecardCardnos, 
        @RequestParam("uptSignInTimes") String[] uptSignInTimes, 
        @RequestParam("uptSignOutTimes") String[] uptSignOutTimes,
        @RequestParam("corpIds") String[] corpIds) throws Exception {
        SysUserEntity user = this.getCurrentUser().getUser();
        // 封装成list
        List<BaseDriverExamUploadErrEntity> list = baseDriverExamInfoService.packToList(user.getCorpId(), uptErrorIds, uptOprtLines, uptLicPltNos, uptDrvNames, uptTimecardCardnos, uptSignInTimes, uptSignOutTimes);
        // 校验导入的数据
        boolean hasAbnormalData = checkDrvExamFilter.doCheck(corpIds[0], list);
        // 存入对应的库表
        baseDriverExamInfoService.saveToDB(corpIds[0], list);
        
//        if(PubUtil.isNotEmpty(conditionVo)){
//            UptEnerConsProcessor processor = new UptEnerConsProcessor(taskExecutor, baseDriverExamInfoService, conditionVo);
//            processor.process();// 对应更新能耗表信息
//        }
        return this.getReturnResult(hasAbnormalData);
    }
    
    /**
     * @param qImportDate
     * @param qErrorType
     * @throws Exception
     * @author:JeffXu
     * @email:835264047@qq.com
     * @创建日期:2014-8-18
     * @功能说明：
     */
    @RequestMapping("/getDriverExamUploadErrList")
    @ResponseBody
    public Object getDriverExamUploadErrList(
        @RequestParam(value = "licPltNo", required=false) String licPltNo,
        @RequestParam(value="qImportDate", required=false) String qImportDate,
        @RequestParam(value="qErrorType", required=false) String qErrorType,
        @RequestParam(value="corpId", required=false) String corpId) throws Exception {
        SysUserEntity user = this.getCurrentUser().getUser();
        List<BaseEntity> list = baseDriverExamInfoService.searchDriverExamUploadErrList(licPltNo,corpId, qImportDate, qErrorType);
        return this.getReturnResult(list);
    }
    
    /**
     * @param errorId
     * @throws Exception
     * @author:JeffXu
     * @email:835264047@qq.com
     * @创建日期:2014-8-19
     * @功能说明：删除考勤上传错误信息
     */
    @RequestMapping("/delErrInfo")
    @ResponseBody
    public Object delErrInfo(@RequestParam("errorId") String errorId) throws Exception {
        baseDriverExamInfoService.delErrInfo(errorId);
        return this.getReturnMsg("删除成功");
    }
    
    /**
     * @param errorIds
     * @throws Exception
     * @author:JeffXu
     * @email:835264047@qq.com
     * @创建日期:2015-1-8
     * @功能说明：批量删除考勤上传错误信息
     */
    @RequestMapping("/delErrInfos")
    @ResponseBody
    public Object delErrInfos(@RequestParam("errorIds") String[] errorIds) throws Exception {
        baseDriverExamInfoService.delErrInfos(errorIds);
        return this.getReturnMsg("删除成功");
    }
    
    /**
     * @param request
     * @param response
     * @throws Exception
     * @author:JeffXu
     * @email:835264047@qq.com
     * @创建日期:2014-8-26
     * @功能说明：导入文件的下载
     */
    @RequestMapping("/downloadDrvExamImptemplate")
    public void downloadDrvExamImptemplate(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String fileName = "driverExamImpTemplate.xls";
        String targetPath = FileUploadUtil.getWebRoot(request) + "/template/" + fileName;
        File tempFile = new File(targetPath);
        if(!tempFile.exists()){
            throw new BusinessException(MsgType.WARN.getFlag(), "没有模版可以下载！");
        }
        ExportUtil.GeneratorLoadFile(targetPath, fileName.substring(0, fileName.lastIndexOf('.')),response);
    }
    
}
